<template>
  <div class="chart-settings">
    <a-form layout="vertical">
      <!-- 图表标题设置 -->
      <a-form-item label="标题">
        <a-input v-model:value="localOptions.title.text" placeholder="请输入图表标题" />
      </a-form-item>
      
      <a-form-item label="显示标题">
        <a-switch v-model:checked="localOptions.title.show" />
      </a-form-item>
      
      <!-- X轴设置 -->
      <a-divider>X轴设置</a-divider>
      
      <a-form-item label="X轴名称">
        <a-input v-model:value="localOptions.xAxis.name" placeholder="请输入X轴名称" />
      </a-form-item>
      
      <a-form-item label="数据类别">
        <a-textarea 
          v-model:value="xAxisData"
          placeholder="请输入数据类别，用逗号分隔" 
          :auto-size="{ minRows: 2, maxRows: 6 }"
        />
      </a-form-item>
      
      <!-- Y轴设置 -->
      <a-divider>Y轴设置</a-divider>
      
      <a-form-item label="Y轴名称">
        <a-input v-model:value="localOptions.yAxis.name" placeholder="请输入Y轴名称" />
      </a-form-item>
      
      <!-- 数据系列设置 -->
      <a-divider>数据系列</a-divider>
      
      <a-collapse v-model:activeKey="activeSeriesKeys">
        <a-collapse-panel 
          v-for="(series, index) in localOptions.series" 
          :key="'series-' + index"
          :header="`数据系列 ${index + 1}: ${series.name || '未命名'}`"
        >
          <a-form-item label="系列名称">
            <a-input v-model:value="series.name" placeholder="请输入系列名称" />
          </a-form-item>
          
          <a-form-item label="数据值">
            <a-textarea 
              v-model:value="seriesDataValues[index]"
              placeholder="请输入数据值，用逗号分隔" 
              :auto-size="{ minRows: 2, maxRows: 6 }"
              @blur="updateSeriesData(index)"
            />
          </a-form-item>
          
          <a-form-item label="柱状颜色">
            <a-input 
              v-model:value="series.itemStyle.color" 
              placeholder="如: #1890ff" 
              :addon-before="'颜色'"
            />
          </a-form-item>
        </a-collapse-panel>
      </a-collapse>
      
      <a-divider></a-divider>
      
      <a-button type="dashed" block @click="addSeries">
        <plus-outlined /> 添加数据系列
      </a-button>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';

const props = defineProps({
  options: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:options']);

// 本地存储options，用于编辑
const localOptions = ref<any>({
  title: {
    text: '',
    show: false
  },
  tooltip: {},
  xAxis: {
    name: '',
    data: []
  },
  yAxis: {
    name: '',
    type: 'value'
  },
  series: [
    {
      name: '系列1',
      type: 'bar',
      data: [],
      itemStyle: {
        color: '#1890ff'
      }
    }
  ]
});

// 用于Collapse的活动面板
const activeSeriesKeys = ref<string[]>(['series-0']);

// 用于输入框绑定的系列数据字符串
const seriesDataValues = ref<string[]>([]);

// X轴数据的字符串形式，用于输入框
const xAxisData = computed({
  get() {
    return localOptions.value.xAxis.data.join(', ');
  },
  set(val: string) {
    const items = val.split(',').map(item => item.trim());
    localOptions.value.xAxis.data = items;
    emitUpdate();
  }
});

// 初始化
onMounted(() => {
  // 深拷贝props的options
  if (props.options) {
    localOptions.value = JSON.parse(JSON.stringify(props.options));
    
    // 确保必要的属性存在
    if (!localOptions.value.title) {
      localOptions.value.title = { text: '', show: false };
    }
    
    if (!localOptions.value.xAxis) {
      localOptions.value.xAxis = { name: '', data: [] };
    }
    
    if (!localOptions.value.yAxis) {
      localOptions.value.yAxis = { name: '', type: 'value' };
    }
    
    if (!localOptions.value.series || !localOptions.value.series.length) {
      localOptions.value.series = [{
        name: '系列1',
        type: 'bar',
        data: [],
        itemStyle: {
          color: '#1890ff'
        }
      }];
    }
    
    // 初始化系列数据字符串
    initSeriesDataValues();
  }
});

// 初始化系列数据字符串
const initSeriesDataValues = () => {
  seriesDataValues.value = localOptions.value.series.map((series: any) => {
    return series.data.join(', ');
  });
};

// 更新系列数据
const updateSeriesData = (index: number) => {
  const dataValues = seriesDataValues.value[index].split(',').map(item => {
    const num = parseFloat(item.trim());
    return isNaN(num) ? 0 : num;
  });
  
  localOptions.value.series[index].data = dataValues;
  emitUpdate();
};

// 添加新的数据系列
const addSeries = () => {
  const newIndex = localOptions.value.series.length;
  localOptions.value.series.push({
    name: `系列${newIndex + 1}`,
    type: 'bar',
    data: Array(localOptions.value.xAxis.data.length).fill(0),
    itemStyle: {
      color: getRandomColor()
    }
  });
  
  // 更新系列数据字符串
  seriesDataValues.value.push('0');
  
  // 添加新系列到激活的keys
  activeSeriesKeys.value.push(`series-${newIndex}`);
  
  emitUpdate();
};

// 生成随机颜色
const getRandomColor = () => {
  const colors = ['#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1', '#13c2c2', '#eb2f96'];
  return colors[Math.floor(Math.random() * colors.length)];
};

// 向父组件发送更新的options
const emitUpdate = () => {
  emit('update:options', localOptions.value);
};

// 监听props.options变化
watch(() => props.options, (newOptions) => {
  if (newOptions) {
    localOptions.value = JSON.parse(JSON.stringify(newOptions));
    initSeriesDataValues();
  }
}, { deep: true });
</script>

<style scoped>
.chart-settings {
  padding: 10px;
}
</style> 